import { NextApiRequest, NextApiResponse } from 'next';
import { withIronSessionApiRoute } from 'iron-session/next';
import { ironOptions } from '@/config/index';
import { prepareConnection } from '@/db/index';
import { Comment, User, Article } from '@/db/entity/index';
import { ISession } from '..';
import { EXCEPTION_COMMENT } from '@/pages/api/config/codes';

const update = async (req: NextApiRequest, res: NextApiResponse) => {
  const session: ISession = req.session;
  const { articleId, content = '' } = req.body;
  const db = await prepareConnection();
  const commentRepo = db.getRepository(Comment);

  const comment = new Comment();
  comment.content = content
  comment.create_time = new Date()
  comment.update_time = new Date()

  const user = await db.getRepository(User).findOne({
    id: session.userId,
  })

  const article = await db.getRepository(Article).findOne({
    id: articleId
  })

  user && (comment.user = user)
  article && (comment.article = article)

  const resComment = await commentRepo.save(comment)

  const allComments = await commentRepo.find({
    where: {
      article: articleId,
    },
    relations: ['user'],
  })

  if (resComment) {
    res.status(200).json({
      code: 200,
      msg: '发布成功',
      data: allComments
    })
  } else {
    res.status(200).json({
      ...EXCEPTION_COMMENT.PUBLISH_FAILED,
    });
  }
}

export default withIronSessionApiRoute(update, ironOptions);